package com.ojoin.trade.common.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ojoin.trade.common.web.domain.Area;
import com.ojoin.trade.common.web.domain.BaseEntity;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.service.SysAreaService;
import com.ojoin.trade.common.web.service.SysManageService;

@Controller
@RequestMapping(value = "sys/area")
public class SysAreaController extends SimpleBaseController {

	@Autowired
	private SysAreaService areaService;
	
	@Autowired
	private SysManageService systemService;

	
	@ModelAttribute("area")
	public Area get(@RequestParam(required=false) Integer id) {
		if (null!=id){
			return  areaService.queryById(id);
		}else{
			return new Area();
		}
	}

	@RequiresPermissions("sys:area:view")
	@ResponseBody
	@RequestMapping(value = "list")
	public Result list() {
		List<Area> list = Lists.newArrayList();
		List<Area> sourcelist = systemService.getAreaList();
		Area.sortList(list, sourcelist, 0, true);
		return new Result(Result.Status.OK,list);
	}

	
	@RequiresPermissions("sys:area:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public Result save(Area area) {
		areaService.insertTree(area);
		return new Result(Result.Status.OK,"保存区域'" + area.getName() + "'成功");
	}
	
	@RequiresPermissions("sys:area:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public Result delete(Area area) {
		area.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
		areaService.delete(area);
		return new Result(Result.Status.OK, "删除区域成功");
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public Result treeData(@RequestParam(required=false) Integer extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Area> list = areaService.queryAll();
		for (int i=0; i<list.size(); i++){
			Area e = list.get(i);
			if (null==extId|| (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return new Result(Result.Status.OK, mapList);
	}
}
